package com.glasses.business.fragment;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.glasses.business.R;
import com.glasses.business.activity.WebDetailActiviy;
import com.glasses.business.adapter.CheckLightAdapter;
import com.glasses.business.adapter.LightPopAdapter;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.AppBaseFragment;
import com.glasses.business.base.MyBaseAdapter;
import com.glasses.business.entity.CheckAttr;
import com.glasses.business.entity.CheckList;
import com.glasses.business.entity.NewsList;
import com.glasses.business.http.NetUtils;
import com.glasses.business.inter.OnItemClick;
import com.glasses.business.utils.Tools;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.neiquan.applibrary.wight.RefreshLayout;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.ToastUtil;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/7
 * Version：1.0
 */

public class CheckLightListFragment extends AppBaseFragment implements RefreshLayout.RetryListener, XRecyclerView.LoadingListener {

    @InjectView(R.id.lightArea)
    TextView lightArea;
    @InjectView(R.id.lightType)
    TextView lightType;
    @InjectView(R.id.lightSpecial)
    TextView lightSpecial;
    @InjectView(R.id.recyclerview)
    XRecyclerView mRecyclerview;
    @InjectView(R.id.refesh_ly)
    RefreshLayout mRefeshLy;
    private CheckLightAdapter checkLightAdapter;
    private RecyclerView mRecylerView_;
    private LightPopAdapter attrAdapter;
    private int pageNum = 0;
    private int PageSize = 10;
    private int attrId = -1;

    @Override
    public int getRootViewId() {
        return R.layout.fragment_light_list;
    }

    @Override
    public void setViews() {
        checkLightAdapter = new CheckLightAdapter(getActivity(), null);
        mRecyclerview.setAdapter(checkLightAdapter);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setOrientation(StaggeredGridLayoutManager.VERTICAL);
        mRecyclerview.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerview.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerview.setArrowImageView(R.mipmap.iconfont_downgrey);
        mRecyclerview.setHasFixedSize(true);
        mRecyclerview.setLayoutManager(layoutManager);
        mRefeshLy.setRetryListener(this);

        mRecyclerview.setLoadingListener(this);
        mRecyclerview.setLoadingMoreEnabled(false);
        mRecyclerview.setPullRefreshEnabled(true);

        checkLightAdapter.setOnItemClickListener(new MyBaseAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, List data, int position) {
                CheckList checkList = (CheckList) data.get(position);
                Bundle bundle = new Bundle();
                bundle.putString("title", "验科详情");
                bundle.putString("url", checkList.getUrl());
                Intent intent = new Intent(getActivity(), WebDetailActiviy.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {
        setTitleTv("附近眼科列表");
        setNextImage(R.mipmap.icon_ss);
        setNextOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                open(new SearchFragment());
            }
        });
        loadDatas(true);
    }

    private void loadDatas(final boolean isRefush) {
        Location location = MyApplication.getInstance().location;
        double latitude = 0;
        double longitude = 0;
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
        Tools.showDialog(getActivity());
        NetUtils.getInstance().checkAddrs(null, latitude, longitude, pageNum, PageSize, attrId, new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                mRecyclerview.loadMoreComplete();
                mRecyclerview.refreshComplete();
                mRefeshLy.hideAll();
                List<CheckList> list = (List<CheckList>) model.getModelList();
                if (isRefush) {
                    checkLightAdapter.clear();
                }
                checkLightAdapter.append(list);
                if (list == null || list.size() < 10) {
                    if (isRefush && (list == null || list.size() == 0)) {
//                        mRefeshLy.showEmptyView();
                        mRefeshLy.showFailView();
                    }
                    mRecyclerview.setLoadingMoreEnabled(false);
                } else {
                    mRecyclerview.setLoadingMoreEnabled(true);
                }
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                //                mRefeshLy.hideAll();
                mRefeshLy.showFailView();
                mRecyclerview.loadMoreComplete();
                mRecyclerview.refreshComplete();
            }
        }, CheckList.class);
    }

    @Override
    public boolean mainTabShow() {
        return false;
    }


    @OnClick({R.id.lightArea, R.id.lightType, R.id.lightSpecial})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lightArea:
                changeTextColor(lightArea, lightType, lightSpecial);
                showPopupWindow(1, lightArea);
                break;
            case R.id.lightType:
                changeTextColor(lightType, lightArea, lightSpecial);
                showPopupWindow(2, lightType);
                break;
            case R.id.lightSpecial:
                changeTextColor(lightSpecial, lightType, lightArea);
                showPopupWindow(3, lightSpecial);
                break;
        }
    }

    @Override
    public void onRetryClick() {
        pageNum = 0;
        loadDatas(true);
    }

    @Override
    public void onRefresh() {
        pageNum = 0;
        loadDatas(true);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        loadDatas(false);
    }


    private void changeTextColor(TextView mTv1, TextView mTv2, TextView mTv3) {
        mTv1.setTextColor(getResources().getColor(R.color.red));
        mTv2.setTextColor(getResources().getColor(R.color.text_gray));
        mTv3.setTextColor(getResources().getColor(R.color.text_gray));
    }

    private void showPopupWindow(int type, final View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.light_pop_window, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.wheel_bg));
        // 设置好参数之后再show
//        popupWindow.showAsDropDown(view);

        mRecylerView_ = ((RecyclerView) contentView.findViewById(R.id.mRecylerView));
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,
                StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setOrientation(StaggeredGridLayoutManager.VERTICAL);
        mRecylerView_.setLayoutManager(layoutManager);
        attrAdapter = new LightPopAdapter(getActivity(), null);
        mRecylerView_.setAdapter(attrAdapter);
        attrAdapter.setOnItemClick(new OnItemClick() {
            @Override
            public void onItemClick(int type, Object obj) {
                CheckAttr checkAttr = (CheckAttr) obj;
                attrId = checkAttr.getId();
                popupWindow.dismiss();
                onRefresh();
            }
        });
//        attrAdapter.setOnItemClickListener(new MyBaseAdapter.OnRecyclerViewItemClickListener() {
//
//            @Override
//            public void onItemClick(View view, List data, int position) {
//                CheckAttr checkAttr = ((CheckAttr) data.get(position));
//                attrId = checkAttr.getId();
//                popupWindow.dismiss();
//            }
//        });
        Tools.showDialog(getActivity());
        NetUtils.getInstance().checkAttr(type, new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                List<CheckAttr> list = (List<CheckAttr>) model.getModelList();
                if (list != null && list.size() > 0) {
                    popupWindow.showAsDropDown(view);
                    attrAdapter.appendAll(list);
                }
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, CheckAttr.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
